#ifndef THREAD_POOL_H
#define THREAD_POOL_H

#include "Common.h"
#include <assert.h>
#include <vector>
#include <pthread.h>
#include "EventLoopThread.h"

// class EventLoop;
// class EventLoopThread;


class ThreadPool {
public:
	ThreadPool(EventLoop *loop, int threadNum):mainLoop_(loop), threadNums_(threadNum) {
		pos_ = 0;
		started_ = 0;
		eventLoopThreads_ = NULL;
	}

	void start() {
		assert(!started_);
		assert(mainLoop_->owner_thread_id_ == pthread_self());

		started_ = 1;

		// printf("ThreadPool Start %d\n", started_);
		
		if (threadNums_ <= 0) {
			return;
		}

		eventLoopThreads_ = (EventLoopThread *)malloc(threadNums_ *  sizeof(EventLoopThread));
		
		for (int i = 0; i < threadNums_; ++i) {
			eventLoopThreads_[i].loopThreadInit(i);
			eventLoopThreads_[i].loopThreadStart(i);
		}
	}


	EventLoop *getNextLoop() {
		assert(started_);
		assert(mainLoop_->owner_thread_id_ == pthread_self());
	
		EventLoop *selected = mainLoop_;

		if (threadNums_ > 0) {
			selected = eventLoopThreads_[pos_].loop_;
			if (++pos_ >= threadNums_) {
				pos_ = 0;
			}
		}
		return selected;		
	}

// private:
	EventLoop *mainLoop_;     
	EventLoopThread* eventLoopThreads_;
	
	int started_;
	int threadNums_;
	int pos_;
};


#endif

